import Vue from 'vue'
import VueRouter from 'vue-router'

// import routes from './routes'

//基础路由表（公共路由表）
let routes = [
  {
    path: '/login',
    name: 'login',
    meta: { title: '登录' },
    component: () => import('../views/Login.vue')
  },
  { //重定向路由,
    path: '/',
    redirect: '/index' //路由重定向,即打开页面时直接显示的那个页面，每一级路由都可以加，要加在最后
  },
  { //404 路由
    path: '*', // * 表示 匹配所有路由地址，善后处理所有路由匹配不到，就跳这个
    name: 'NotFound',
    meta: { title: 'NotFound' },
    component: () => import('../views/NotFound.vue')
  }
]


Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 设置导航守卫
router.beforeEach((to, from, next) => {
  //动态修改网页标题
  document.title = to.meta.title;

  //获取token
  var token = localStorage.getItem('token');
  if (to.path == '/login' || to.path == '/register') {
    if (token) {
      next('/index');
    } else {
      next()
    }
  } else {
    if (token) {
      next();
    } else {
      next('/login');
    }
  }

})

export default router
